#include <iostream>
#include <unistd.h>
#include <pthread.h>

// 全局的，属于各个线程共享的资源，其相关接口的操作都是原子性的
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    // 定义全局的cond
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 定义全局的锁
int ticket = 1000;
void *function(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        // 有票
        if (ticket > 0)
        {
            std::cout << name << ", get a ticket : " << ticket-- << std::endl;
        }
        // 没票
        else
        {
            // 没有票，就去排队等待
            std::cout << name << ", 没有票了" << std:: endl;
            pthread_cond_wait(&cond, &mutex);
            std::cout << name << "唤醒了" << std:: endl;
        }
        pthread_mutex_unlock(&mutex);
        usleep(1000);
    }
    return nullptr;
}
int main()
{
    pthread_t t1;
    pthread_create(&t1, nullptr, function, (void *)"thread-1");

    pthread_t t2;
    pthread_create(&t2, nullptr, function, (void *)"thread-2");

    pthread_t t3;
    pthread_create(&t3, nullptr, function, (void *)"thread-3");

    // 主线程
    while (true)
    {
        sleep(5);
        pthread_mutex_lock(&mutex);
        // std::cout << "main get mutex" << std::endl;
        if (ticket == 0)
        {   
            ticket = 1000;
            pthread_cond_signal(&cond);
            // pthread_cond_broadcast(&cond);
        }
        pthread_mutex_unlock(&mutex);
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    return 0;
}